package com.zlp.partice.io.bio.file;

import com.zlp.partice.util.DateUtil;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: zhulaiping
 * @time: 2022/8/8 10:45
 */
public class BioDemo1_Server1 {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        ExecutorService executorService =
                new ThreadPoolExecutor(3,3,120, TimeUnit.SECONDS,new ArrayBlockingQueue<>(10));
        while (true){
            Socket socket = serverSocket.accept();
            Runnable task = new ServerRunnable(socket);
            executorService.execute(task);
        }
    }


    static class ServerRunnable implements Runnable{

        private Socket socket;

        public ServerRunnable(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            try {

                BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
                String fileName = DateUtil.getYMDHMS(new Date());
                FileOutputStream fos = new FileOutputStream("D:\\io\\"+fileName+".jpg");
                byte[] buffer = new byte[1024];
                int len;
                while ((len = bis.read(buffer))!=-1){
                    fos.write(buffer,0,len);
                }
                fos.close();
                PrintStream ps = new PrintStream(socket.getOutputStream());
                ps.println("文件上传成功");
                socket.shutdownInput();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
